# -*- coding:utf-8 -*-

import json,xlrd
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By


class basepage(object):

    #构造函数
    def __init__(self,driver,time=3):
        '''
        :param driver: 传入WebDriver
        :param time: 隐式等待时间,默认3秒
        '''
        self.driver = driver
        self.driver.maximize_window()
        self.driver.implicitly_wait(time)

    #访问url
    def AccessUrl(self,url):
        self.driver.get(url)

    # 显式等待
    def AccordingWait(self, method, locator, node, total=3, interval=1):
        '''
        :param method: 定位方式
        :param locator: 元素路径
        :param node: 是否多路径
        :param total: 总共等待时间
        :param interval: 等待间隔
        :return: 元素定位路径
        '''
        if node == 'less':
            Ele = WebDriverWait(self.driver, total, interval).until(
                ec.visibility_of_element_located(
                    (method, locator)
                )
            )
            return Ele
        else:
            Ele = WebDriverWait(self.driver, total, interval).until(
                ec.visibility_of_all_elements_located(
                    (method, locator)
                )
            )
            return Ele

    #元素定位
    def ElementLocalization(self,method,locator,node='less',Sign=True):
        '''
        :param method: 定位方式
        :param locator: 元素路径
        :param Sign: 定位失败是否跳过（True抛出异常，False跳过）
        '''
        try:
            return self.AccordingWait(method,locator,node)
        except Exception as e:
            if Sign:
                raise
            else:
                return False



    #元素点击
    def ElementClick(self,method,locator,node='less',Sign=True):
        '''
        :param method: 定位方式
        :param locator: 元素路径
        '''
        self.ElementLocalization(method,locator,node,Sign).click()

    #输入文本
    def ElementInput(self,method,locator,text,node='less',Sign=True):
        '''
        :param method: 定位方式
        :param locator: 元素路径
        :param text: 输入文本
        '''
        self.ElementLocalization(method,locator,node,Sign).send_keys(text)

    #获取文本
    def GetElementText(self,method,locator,node='less',Sign=True):
        '''
        :param method: 定位方式
        :param locator: 元素路径
        '''
        text = self.ElementLocalization(method, locator,node,Sign).text
        return text

    # 清除文本
    def ClearElementText(self,method,locator,node='less',Sign=True):
        '''
        :param method: 定位方式
        :param locator: 元素路径
        '''
        local = self.ElementLocalization(method, locator,node,Sign)
        local.clear()



    #等待元素消失,消失后返回True
    def ExistenceWaite(self,method,locator,total=3,interval=1):
        '''
        :param method: 定位方式
        :param locator: 元素路径
        :param total: 总共等待时间
        :param interval: 等待间隔
        :return: bool
        '''
        try:
            WebDriverWait(self.driver,total,interval).until_not(
                ec.presence_of_element_located
                    (method,locator)
            )
        except Exception:
            return False
        return True

    #移动游标
    def MoveCursor(self,method,locator):
        '''
        :param method: 定位方式
        :param locator: 元素路径
        '''
        pass

    #切换iframe
    def ChangeFrame(self,num=0):
        '''
        :param num: 默认进入第一次iframe
        '''
        iframe = self.driver.find_elements_by_tag_name('iframe')[num]
        return self.driver.switch_to.frame(iframe)

    #释放iframe
    def ReleaseFrame(self):
        self.driver.switch_to.default_content()

    #判断元素是否存在
    def AreThere(self, method, locator,node='less'):
        '''
        :param method: 定位方式
        :param locator: 元素路径
        :param return: bool
        '''
        Flag = True
        try:
            self.ElementLocalization(method, locator,node)
            return Flag
        except:
            Flag = False
            return Flag

    #页面缩放
    def PageZoom(self,num=0.5):
        '''
        :param num: 缩放比例
        '''
        zoom = "document.body.style.zoom='{}'".format(num)
        self.driver.excute_script(zoom)

    #改变元素标签属性
    def ChangeAttribute(self,method,locator,value,txt,node='less',Sign=True):
        path = self.ElementLocalization(method,locator,node,Sign)
        js = 'arguments[0].{}="{}"'.format(value,txt)
        self.driver.execute_script(js,path)

    #内嵌滚动条滚动
    def DivRolling(self,classname,method='div',direction='left', num=0,num2=0):
        '''
        :param classname: 内嵌div的classname
        :param method: 内嵌windows/div
        :param direction: 滚动条滚动方向
        :param num: 左边距
        :param num2: 上边距
        '''
        try:
            if method == 'div':
                if direction == 'top':
                    js = 'document.getElementsByClassName("{}")[0].scrollTop={}'.format(classname, num)
                    self.driver.execute_script(js)
                elif direction == 'left':
                    js = 'document.getElementsByClassName("{}")[0].scrollLeft={}'.format(classname, num)
                    self.driver.execute_script(js)
                else:
                    pass
            if method == 'window':
                js = "window.scrollTo({},{})".format(num, num2)
                return self.driver.execute_script(js)
        except Exception as e:
            raise e

    #获取当前页面URL
    def GetUrl(self):
        return self.driver.current_url

    #切换到新的窗口句柄
    def ChangeHandle(self):
        # 获取当前所有句柄
        handles = self.driver.window_handles
        return self.driver.switch_to_window(handles[-1])

